/*
 * Copyright (c) 2006-2008 Reliable Source, Inc and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Mozilla Public License v.1.1
 * and BSD licenses.
 * 
 * http://www.eclipse.org/legal/epl-v10.html
 * http://www.opensource.org/licenses/bsd-license.php
 * http://www.mozilla.org/MPL/MPL-1.1.html
 *
 * Contributors:
 *      IBM Corporation - initial API and implementation
 *      patientos.org - domain and database persistence layer              
 *      Reliable Source, Inc. - user interface client platform
 *
 */
package org.reliablesource.client.ui.workbench.views;

import java.util.HashMap;

import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.commands.common.CommandException;
import org.eclipse.jface.viewers.IOpenListener;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.contexts.IContextService;
import org.eclipse.ui.handlers.IHandlerService;
import org.eclipse.ui.services.IServiceLocator;
import org.reliablesource.client.ui.workbench.WorkbenchActivator;

/**
 * 
 * ReliableOpenListener.java<br>
 * Created on: Jun 26, 2008<br>
 *
 * @author <a href="mailto:dennis.park@gmail.com">Dennis Park</a>
 *
 * @category
 * @since 1.0
 */
public class ReliableOpenListener implements IOpenListener {

    /** The String literal of the double-click commands' command id. */
    public static final String DBL_CLICK_CMD = 
	"org.reliablesource.client.ui.symbiosys.platform.open.details";

    /** A reference to the workbenchs' command service framework. */
    protected ICommandService commandService;
    protected IContextService contextService;

    /** A reference to this parts' double click handler. */
    protected IHandler handler;

    /** A reference to the workbenchs' handler service framework. */
    protected IHandlerService handlerService;
    protected IServiceLocator services;
    
    

    /*
     * (non-Javadoc)
     *
     * @see org.eclipse.jface.viewers.IOpenListener#open(org.eclipse.jface.viewers.OpenEvent)
     */
    public void open(final OpenEvent event) {
        
        services = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
        .getActivePage().getActivePart().getSite();
        
        commandService = (ICommandService) services
                .getService(ICommandService.class);
        handlerService = (IHandlerService) services
                .getService(IHandlerService.class);
        contextService = (IContextService) services
                .getService(IContextService.class);
        
        
        try {
            Command _cmd =
                commandService.getCommand(DBL_CLICK_CMD);
            if (_cmd == null) {
                throw (new ReliableWorkbenchRuntimeException("Command not found.",
                        WorkbenchActivator.PLUGIN_ID, "Command not found."));
            }

            if (!_cmd.isHandled() && (handler == null)) {
                handler = new OpenInDetailsViewHandler();
                handlerService.activateHandler(DBL_CLICK_CMD, handler);
            }

            // Exceute the command
            execute(_cmd, event);
        } catch (ReliableWorkbenchRuntimeException e) {
            //            Dialog.displayError(e, true);
        } catch (Exception e) {
            //            Dialog.displayError(e, true);

        }
    }

    /**
     * Execute the given command.
     *
     * @param  _cmd  The command to execute.
     * @param  trigger  The object that triggered this execution.
     * @throws  CMPException  If there are any errors while executing the
     *                        command.
     */
    private void execute(Command _cmd, Object trigger) throws ReliableWorkbenchException {
        try {
            
            System.err.println("Current Context: "  +contextService.getActiveContextIds().toArray()[0]);
            
            System.err.println(contextService.getActiveContextIds().toArray().toString());
            // Execute the command
            _cmd.executeWithChecks(new ExecutionEvent(_cmd, new HashMap(),
                    trigger, contextService.getActiveContextIds().toArray()[0]));
//                    ApplicationWorkbenchWindowAdvisor.WINDOW_CONTEXT_ID));
        } catch (ExecutionException _e) {
            Throwable t = _e.getCause();
            if (t instanceof ReliableWorkbenchException)
                throw ((ReliableWorkbenchException) t);

            if (t instanceof ReliableWorkbenchRuntimeException)
                throw ((ReliableWorkbenchRuntimeException) t);

            throw (new ReliableWorkbenchException("Cannot open details view.",
                    WorkbenchActivator.PLUGIN_ID, "Cannot open details view.", _e));
        } catch (CommandException e) {
            throw (new ReliableWorkbenchRuntimeException("Cannot open details view.",
                    WorkbenchActivator.PLUGIN_ID, "Cannot open details view.", e));
        }
    }

}
